﻿using WCS.Entity;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using WcsApi.Models;
using WCSApi;
using SqlSugar;
using System.Reflection;
using API.SqlSugar;
using static WcsAip.Controllers.PDAController;

namespace WcsApi.Controllers
{
    /// <summary>
    /// 任务控制器
    /// </summary>
    [Route("[controller]/[action]")]
    [ApiExplorerSettings(GroupName = "3")]
    [ApiController]
    public class DevController : Controller
    {
        static SqlSugarDapper _sqlSugarDapper = SqlSugarDapper.GetDbContext();

        public List<int> lists = new List<int>();

        Dictionary<string, string> mater = new Dictionary<string, string>();
        /// <summary>
        /// 获取库存
        /// </summary>
        /// <param name="code">仓库编号</param>
        /// <returns></returns>
        [HttpGet]
        public Result<WarehouseInfo> GetStock(string code)
        {
            try
            {
                var i = _sqlSugarDapper.DB.SqlQueryable<WarehouseInfo>("SELECT *,DATEDIFF(MINUTE, CreateTime,GETDATE()) as dataIff from WCS_WarehouseInfo order by [index]").ToList();

                var result = Result<WarehouseInfo>.jsonResult(i, 0, "success");

                return result;
            }
            catch (Exception ex)
            {
                var result = Result<WarehouseInfo>.error(ex.Message);

                return result;
            }
        }

        /// <summary>
        /// 获取库存
        /// </summary>
        /// <param name="code">仓库编号</param>
        /// <returns></returns>
        [HttpGet]
        public DataView GetData()
        {
            try
            {
                DataView dataView = new DataView();
                dataView.inTask = new List<WarehouseInfoView>();
                dataView.outTask = new List<WarehouseInfoView>();
                dataView.Expire = new List<WarehouseInfoView>();
                dataView.OutRecords = new List<WarehouseInfoView>();
                dataView.readTrayCodes = new List<WcsReadTrayCode>();
                dataView.wendu = new Wendu();
                dataView.callNumbers = new CallMaterialView();
                dataView.materialCounts = new List<MaterialCount>();
                dataView.CallTasks = new List<CallTasks>();

                var inTask = _sqlSugarDapper.DB.Queryable<WcsTaskConveyor>().Where(w => w.Task_Type == "in").ToList();
                foreach (var item in inTask)
                {
                    dataView.inTask.Add(new WarehouseInfoView
                    {
                        barCode = item.TrayBar_Code.Substring(item.TrayBar_Code.Length - 3),
                        materilCode = item.TrayBar_Code.Substring(6, 8),
                        WarehouseCode = item.End_Station + "-" + item.WMSBinCode,
                        materilName = item.MaterialType,
                        CreateTime = item.CreateTime.ToString().Substring(10, 5),
                    });
                }

                var outTask = _sqlSugarDapper.DB.Queryable<WcsTaskConveyor>().Where(w => w.Task_Type == "out").ToList();
                foreach (var item in outTask)
                {
                    dataView.outTask.Add(new WarehouseInfoView
                    {
                        barCode = item.TrayBar_Code.Substring(item.TrayBar_Code.Length - 3),
                        materilCode = item.TrayBar_Code.Substring(6, 8),
                        WarehouseCode = item.End_Station + "-" + item.WMSBinCode,
                        materilName = item.MaterialType,
                        CreateTime = item.CreateTime.ToString().Substring(10, 5),
                    });
                }

                var warehouseInfos = _sqlSugarDapper.DB.SqlQueryable<WarehouseInfo>("SELECT *,DATEDIFF(MINUTE, CreateTime,GETDATE()) as dataIff from WCS_WarehouseInfo").OrderBy(o => o.index).ToList();

                dataView.werhous = warehouseInfos.Count;
                foreach (var item in warehouseInfos.FindAll(f => f.dataIff >= (6 * 1440)))
                {
                    var time = DateTime.Now;
                    var Hours = 0;
                    var minuteSpan = 0;
                    var data = "";

                    var day7 = item.CreateTime.AddDays(7);

                    if (time > day7)
                    {
                        Hours = new TimeSpan(time.Ticks - day7.Ticks).Hours;
                        minuteSpan = (int)new TimeSpan(time.Ticks - day7.AddHours(Hours).Ticks).TotalMinutes;
                        data = $"-{Hours}h {minuteSpan}min";
                    }
                    else
                    {
                        Hours = new TimeSpan(day7.Ticks - time.Ticks).Hours;
                        minuteSpan = (int)new TimeSpan(day7.Ticks - time.AddHours(Hours).Ticks).TotalMinutes;
                        data = $"{Hours}h {minuteSpan}min";
                    }

                    dataView.Expire.Add(new WarehouseInfoView
                    {
                        barCode = item.barCode.Substring(item.barCode.Length - 3),
                        materilCode = item.barCode.Substring(6, 8),
                        WarehouseCode = item.ID,
                        materilName = _sqlSugarDapper.DB.Queryable<PalletToMaterial>().Where(w => w.PalletCode.Contains(item.barCode.Substring(6, 8))).First().MaterialType,
                        CreateTime = item.CreateTime.ToString().Replace("/", "-"),
                        dataIff = data,
                    });
                }

                var nowDt = DateTime.Now;
                var workStartDT = DateTime.Parse("8:00");
                var workEndDT = DateTime.Parse("20:00");
                List<WarehouseIO> outRecords = new List<WarehouseIO>();

                //白班还是晚班
                if (nowDt > workStartDT && nowDt < workEndDT)
                {
                    //白班
                    outRecords = _sqlSugarDapper.DB.SqlQueryable<WarehouseIO>($"Select BarCodeData,ID,Task_type, COUNT(*) as Qty from WCS_WarehouseIO where CreateTime >= '{workStartDT}' and CreateTime <= '{workEndDT}' group by BarCodeData, ID,Task_type").ToList();
                }
                else
                {
                    //晚班
                    outRecords = _sqlSugarDapper.DB.SqlQueryable<WarehouseIO>($"Select BarCodeData,ID,Task_type, COUNT(*) as Qty from WCS_WarehouseIO where CreateTime <= '{workStartDT.AddDays(1)}' and CreateTime >= '{workEndDT}' group by BarCodeData, ID,Task_type").ToList();
                }

                foreach (var item in outRecords)
                {
                    dataView.OutRecords.Add(new WarehouseInfoView
                    {
                        materilCode = item.ID,
                        materilName = item.BarCodeData,
                        Tasktype = item.Task_type == "in" ? "入库" : "出库",
                        Qty = item.Qty
                    });
                }

                dataView.readTrayCodes = _sqlSugarDapper.DB.Queryable<WcsReadTrayCode>().Where(w => w.Remark != "" && w.Station_Plc_No != "B008").ToList();
                dataView.PlcError = _sqlSugarDapper.DB.Queryable<WcsDevPlc>().Where(w => w.Remark != "").First()?.Remark;

                var wcsDev = _sqlSugarDapper.DB.Queryable<WcsDevPlc>().Where(w => w.Dev_Code == "1000").First();
                dataView.wendu.temperature = wcsDev.ATTRIBUTE1 + "℃";
                dataView.wendu.humidity = wcsDev.ATTRIBUTE2 + "%";

                var callMaterialNum = _sqlSugarDapper.DB.Queryable<CallMaterial>()
                    .Where(w => w.isSupply == 0)
                    .ToList();
                dataView.callNumbers.callMaterialCount = callMaterialNum.Count;


                var palletlist = _sqlSugarDapper.DB.Queryable<PalletToMaterial>().ToList();
                //for (int x = 0; x < palletlist.Count; x++)
                //{
                //    mater.Add(palletlist[x].PalletCode, palletlist[x].MaterialType);
                //}
                var msms = _sqlSugarDapper.DB.SqlQueryable<CallMaterial>("SELECT CallStation,isSupply,MaterialType,SupplyNum ,CASE CallStation WHEN '3001' THEN 'D1'WHEN '3002' THEN 'D2' WHEN '3003' THEN 'D3' WHEN '3004' THEN 'D4' WHEN '3005' THEN 'D5' WHEN '3006' THEN 'C1'WHEN '3007' THEN 'C2' WHEN '3008' THEN 'C3' WHEN '3009' THEN 'C4' WHEN '3010' THEN 'C5' ELSE 'null' END FROM WCS_CallMaterial WHERE 1=1").ToList();

                foreach (var item in msms)
                {
                    switch (item.CallStation)
                    {
                        case "3001":
                            item.CallStation = "C1";
                            break;
                        case "3002":
                            item.CallStation = "C2";
                            break;
                        case "3003":
                            item.CallStation = "C3";
                            break;
                        case "3004":
                            item.CallStation = "C4";
                            break;
                        case "3005":
                            item.CallStation = "C5";
                            break;
                        case "3006":
                            item.CallStation = "D1";
                            break;
                        case "3007":
                            item.CallStation = "D2";
                            break;
                        case "3008":
                            item.CallStation = "D3";
                            break;
                        case "3009":
                            item.CallStation = "D4";
                            break;
                        case "3010":
                            item.CallStation = "D5";
                            break;
                        default:
                            break;
                    }
                }

                foreach (var item in msms)
                {
                    dataView.CallTasks.Add(new CallTasks
                    {
                        CallStation= item.CallStation,
                        isSupply=item.isSupply,
                        MaterialType=item.MaterialType,
                        SupplyNum=item.SupplyNum,
                    });
                }

                //没种物料库存数量
                var materiallist = _sqlSugarDapper.DB.SqlQueryable<WarehouseInfo>($"SELECT COUNT(SUBSTRING(barCode, 7, 8)) as num ,CASE SUBSTRING(barCode, 7, 8) WHEN '{palletlist[0].PalletCode}' THEN '{palletlist[0].MaterialType}' WHEN '{palletlist[1].PalletCode}' THEN '{palletlist[1].MaterialType}' WHEN '{palletlist[2].PalletCode}' THEN '{palletlist[2].MaterialType}'WHEN '{palletlist[3].PalletCode}' THEN '{palletlist[3].MaterialType}'WHEN '{palletlist[4].PalletCode}' THEN '{palletlist[4].MaterialType}'WHEN '{palletlist[5].PalletCode}' THEN '{palletlist[5].MaterialType}'WHEN '{palletlist[6].PalletCode}' THEN '{palletlist[6].MaterialType}'WHEN '{palletlist[7].PalletCode}' THEN '{palletlist[7].MaterialType}'WHEN '{palletlist[8].PalletCode}' THEN '{palletlist[8].MaterialType}'WHEN '{palletlist[9].PalletCode}' THEN '{palletlist[9].MaterialType}' ELSE 'null' END AS materialtype FROM WCS_WarehouseInfo WHERE 1=1 GROUP BY SUBSTRING(barCode, 7, 8)").ToList();

                var i = _sqlSugarDapper.DB.SqlQueryable<WarehouseInfo>("SELECT *,DATEDIFF(MINUTE, CreateTime,GETDATE()) as dataIff from WCS_WarehouseInfo order by [index]").ToList();

                foreach (var item in palletlist)
                {
                    if (item.PalletCode == "")
                    {
                        break;
                    }
                    var dd = i.FindAll(w => w.barCode.Contains(item.PalletCode) && w.dataIff >= 120 && w.dataIff <= 10080 && w.state == 55).ToList().Count();
                    //lists.Add(dd);
                    mater.Add(item.MaterialType, dd.ToString());
                }

                foreach (var item in materiallist)
                {
                    dataView.materialCounts.Add(new MaterialCount
                    {
                        materialtype = item.materialtype,
                        num = item.num,
                        allowOutNum = mater.Where(w => w.Key == item.materialtype).Select(w => w.Value).First(),
                    });
                }

                return dataView;
            }
            catch (Exception ex)
            {
                _sqlSugarDapper.DB.Insertable(new ApiLogs(
                    $"{MethodBase.GetCurrentMethod().Name}(获取数据)",
                    JsonConvert.SerializeObject(ex.StackTrace),
                    JsonConvert.SerializeObject(ex.StackTrace))
                ).ExecuteCommand();

                return null;
            }
        }

        /// <summary>
        /// 获取输送线状态
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public Result<DevPlcStationState> GetConveyorState()
        {
            try
            {
                var devPlcStationStates = _sqlSugarDapper.DB.Queryable<DevPlcStationState>().ToList();

                devPlcStationStates.FindAll(f => f.EndWarehouse.Contains("9002")).ForEach(f => f.EndWarehouse = "空托库存");
                devPlcStationStates.FindAll(f => f.EndWarehouse.Contains("9001")).ForEach(f => f.EndWarehouse = "满托库存");

                var result = Result<DevPlcStationState>.jsonResult(devPlcStationStates, 0, "success");

                return result;
            }
            catch (Exception ex)
            {
                var result = Result<DevPlcStationState>.error(ex.Message);

                return result;
            }
        }
    }

    public class DataView
    {
        public List<WarehouseInfoView> inTask { get; set; }
        public List<WarehouseInfoView> outTask { get; set; }
        public List<WarehouseInfoView> Expire { get; set; }
        public List<WarehouseInfoView> OutRecords { get; set; }

        public List<WcsReadTrayCode> readTrayCodes { get; set; }

        public CallMaterialView callNumbers { get; set; }

        public List<MaterialCount> materialCounts { get; set; }
        public Wendu wendu { get; set; }
        public string PlcError { get; set; }

        public int werhous { get; set; }
        public List<CallTasks> CallTasks { get; set; }
    }

    public class Wendu
    {
        public string temperature { set; get; }
        public string humidity { set; get; }
    }


    public class WarehouseInfoView
    {
        /// <summary>
        /// 物料码
        /// </summary>
        public string materilCode { get; set; }

        /// <summary>
        /// 物料名称
        /// </summary>
        public string materilName { get; set; }

        /// <summary>
        /// 料架号
        /// </summary>
        public string barCode { get; set; }

        /// <summary>
        /// 时间
        /// </summary>
        public string CreateTime { get; set; }

        /// <summary>
        /// 库位号
        /// </summary>
        public string WarehouseCode { get; set; }

        /// <summary>
        /// 剩余时间
        /// </summary>
        public string dataIff { get; set; }

        /// <summary>
        /// 剩余时间
        /// </summary>
        public string Tasktype { get; set; }

        /// <summary>
        /// 剩余时间
        /// </summary>
        public int Qty { get; set; }
    }

    public class CallMaterialView
    {
        public int callMaterialCount { get; set; }
    }

    public class MaterialCount
    {
        public string num { get; set; }
        public string allowOutNum { get; set; }
        public string materialtype { get; set; }
    }

    public class CallTasks
    {
        public string CallStation { get; set; }

        public string MaterialType { get; set; }

        public int isSupply { get; set; }

        public int SupplyNum { get; set; }
    }
}